package com.ruoyi.project.comp.h5;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.comp.comment.domain.CompComment;
import com.ruoyi.project.comp.comment.service.ICompCommentService;
import com.ruoyi.project.comp.home.RankDTO;
import com.ruoyi.project.comp.home.StatsDTO;
import com.ruoyi.project.comp.like.domain.CompLike;
import com.ruoyi.project.comp.like.service.ICompLikeService;
import com.ruoyi.project.comp.setting.domain.CompSetting;
import com.ruoyi.project.comp.setting.service.ICompSettingService;
import com.ruoyi.project.comp.share.domain.CompShare;
import com.ruoyi.project.comp.share.service.ICompShareService;
import com.ruoyi.project.comp.work.domain.CompWork;
import com.ruoyi.project.comp.work.service.ICompWorkService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 作品评论Controller
 * 
 * @author ruoyi
 * @date 2025-11-02
 */
@Controller
@RequestMapping("/h5")
public class H5indexController extends BaseController
{

    @Autowired
    private ICompWorkService compWorkService;

    @Autowired
    private ICompLikeService compLikeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICompShareService compShareService;

    @Autowired
    private ICompSettingService compSettingService;



    private String prefix = "h5";

    @Autowired
    private ICompCommentService compCommentService;

    @GetMapping("/index")
    public String index()
    {
        return prefix + "/index";
    }

    @GetMapping("index_huodong")
    public String index_huodong()
    {
        return prefix + "/index_huodong";
    }

    @GetMapping("index_paihangbang")
    public String index_paihangbang()
    {
        return prefix + "/index_paihangbang";
    }

    @GetMapping("index_yonghu")
    public String index_yonghu()
    {
        return prefix + "/index_yonghu";
    }

    @GetMapping("index_baoming")
    public String index_baoming()
    {
        return prefix + "/index_baoming";
    }


    @GetMapping("index_mianze")
    public String index_mianze()
    {
        return prefix + "/index_mianze";
    }

    @GetMapping("/upload")
    public String upload()
    {
        return prefix + "/upload";
    }

    @GetMapping("/upload_bak")
    public String upload_bak()
    {
        return prefix + "/upload_bak";
    }

    @GetMapping("index_zuopin")
    public String index_zuopin(Integer id, ModelMap mmap)
    {
        // 根据id 查看作品
        CompWork compWork = compWorkService.selectCompWorkById(Long.valueOf(id));

        if(compWork != null){
            Integer lookCount = compWork.getLookCount();
            if(lookCount != null){
                compWork.setLookCount(lookCount + 1);
            }else{
                compWork.setLookCount(1);
            }
            compWorkService.updateCompWork(compWork);
        }
//        CompComment compComment = new CompComment();
//        compComment.setWorkId(compWork.getId());
//        List<CompComment> compComments = compCommentService.selectCompCommentList(compComment);
//        int commentCount = 0;
//        if(CollectionUtil.isNotEmpty(compComments)){
//            commentCount = compComments.size();
//        }
//        compWork.setCommentCount(commentCount);

        // 查询该作品的所有评论
        CompComment query = new CompComment();
        query.setWorkId(compWork.getId());
        List<CompComment> allComments = compCommentService.selectCompCommentList(query);
        List<User> allUser = userService.selectUserList(new User());
        // 2. 查询所有用户并构建ID到用户名的映射
        Map<Long, String> userIdToNameMap = new HashMap<>();
        for (User user : allUser) {
            // 假设User类中用户ID字段为id，用户名字段为username
            userIdToNameMap.put(user.getUserId(), user.getUserName());
        }

        // 3. 给每个评论设置用户名（如果存在匹配的用户）
        for (CompComment comment : allComments) {
            Long userId = comment.getUserId();
            // 从映射中获取用户名，不存在则显示默认值
            String username = userIdToNameMap.getOrDefault(userId, "匿名用户");
            comment.setUserName(username); // 需要在CompComment类中添加username字段
        }

        List<CompComment> topComments = new ArrayList<>();
        Map<Long, List<CompComment>> childCommentMap = new HashMap<>();

        for (CompComment comment : allComments) {
            Long pid = comment.getPid();
            if (pid == null || pid == 0) {
                topComments.add(comment);
            } else {
                if (!childCommentMap.containsKey(pid)) {
                    childCommentMap.put(pid, new ArrayList<>());
                }
                childCommentMap.get(pid).add(comment);
            }
        }
        for (CompComment topComment : topComments) {
            List<CompComment> children = childCommentMap.get(topComment.getId());
            if (children != null) {
                // 按评论时间排序（最新的在前面）
                children.sort((c1, c2) -> c2.getCommentTime().compareTo(c1.getCommentTime()));
                topComment.setChild(children); // 需要在CompComment实体类中添加children字段
            }
        }
        topComments.sort((c1, c2) -> c2.getCommentTime().compareTo(c1.getCommentTime()));
        compWork.setCommentCount(allComments.size());
        mmap.put("comments", topComments);
        mmap.put("compWork", compWork);

        return prefix + "/index_zuopin";
    }



    /**
     * 获取统计数据
     */
    @GetMapping("/stats")
    @ResponseBody
    public StatsDTO getStats() {
        StatsDTO stats = new StatsDTO();
        int userCount = 0;
        int compLikeCount = 0;
        int workCount = 0;
        int compShareCount = 0;

        List<User> userList = userService.selectUserList(new User());
        if(CollectionUtil.isNotEmpty(userList)){
            userCount = userList.size();
        }
//        List<CompLike> compLikeList = compLikeService.selectCompLikeList(new CompLike());
//        if(CollectionUtil.isNotEmpty(compLikeList)){
//            compLikeCount = compLikeList.size();
//        }
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        if(CollectionUtil.isNotEmpty(workList)){
            workCount = workList.size();
        }
//        List<CompShare> compShareList = compShareService.selectCompShareList(new CompShare());
//        if(CollectionUtil.isNotEmpty(compShareList)){
//            compShareCount = compShareList.size();
//        }

        long workUserCount = 0L;
        if (CollectionUtil.isNotEmpty(workList)) {
            workUserCount = workList.stream()
                    .map(CompWork::getParticipantUserId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet())        // 收集到 Set 自动去重
                    .size();


            compLikeCount = workList.stream()
                    .map(CompWork::getLikeCount)
                    .filter(Objects::nonNull)  // 过滤掉null值
                    .mapToInt(Integer::intValue)  // 转换为IntStream
                    .sum();

            compShareCount = workList.stream()
                    .map(CompWork::getLookCount)
                    .filter(Objects::nonNull)  // 过滤掉null值
                    .mapToInt(Integer::intValue)  // 转换为IntStream
                    .sum();
        }


        stats.setTotalContestants((int) workUserCount);
        stats.setTotalUsers(userCount);
        stats.setTotalLikes(compLikeCount);
        stats.setTotalViews((long) compShareCount);

        String beginTime = "";
        String endTime = "";
        CompSetting compSetting = compSettingService.selectCompSettingById(1L);
        if(compSetting != null){
            Date beginTimeDate = compSetting.getContestStartTime();
            Date endTimeDate = compSetting.getContestEndTime();
            if(beginTimeDate != null){
                beginTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, beginTimeDate);
                endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTimeDate);
            }
        }
        stats.setBeginTime(beginTime);
        stats.setEndTime(endTime);

        if(compSetting != null){
            Long dailyLike = compSetting.getDailyLikeLimit();
            if(dailyLike != null){
                stats.setLikeCount(String.valueOf(compSetting.getDailyLikeLimit()));
            }else{
                stats.setLikeCount(String.valueOf(5));
            }
        }else{
            stats.setLikeCount(String.valueOf(5));
        }


        return stats;
    }


    /**
     * 获取综合得分TOP10
     */
    @GetMapping("/rank/comprehensive")
    @ResponseBody
    public List<CompWork> getComprehensiveRank() {
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getTotalScore ,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                .collect(Collectors.toList()); // 转换为 List
        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork  = workList.get(i);
            compWork.setIndex(i+1);
        }
        return workList;
    }

    /**
     * 按点赞量
     */
    @GetMapping("/rank/like")
    @ResponseBody
    public List<CompWork> getStudentRank() {
        CompWork queryCompWork = new CompWork();
        queryCompWork.setStatus(1L);
        List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
        workList = workList.stream()
                .sorted(Comparator.comparing(CompWork::getStudentScore ,
                                Comparator.nullsLast(Comparator.reverseOrder()))
                        .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                .collect(Collectors.toList()); // 转换为 List
        for (int i = 0; i < workList.size(); i++) {
            CompWork compWork  = workList.get(i);
            compWork.setIndex(i+1);
        }
        return workList;
    }

    /**
     * 按序号
     */
    @GetMapping("/rank/byid")
    @ResponseBody
    public List<CompWork> getTeacherRank() {
        try{
            CompWork queryCompWork = new CompWork();
            queryCompWork.setStatus(1L);
            List<CompWork> workList = compWorkService.selectCompWorkList(queryCompWork);
            workList = workList.stream()
                    .sorted(Comparator.comparing(CompWork::getId ,
                                    Comparator.nullsLast(Comparator.reverseOrder()))
                            .thenComparing(CompWork::getId)) // 得分相同时，按ID排序（可选）
                    .collect(Collectors.toList()); // 转换为 List
            for (int i = 0; i < workList.size(); i++) {
                CompWork compWork  = workList.get(i);
                compWork.setIndex(i+1);
            }
            return workList;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
